//
//  RTJAutoMarkDetailsController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/12/20.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJAutoMarkDetailsController.h"
#import "MXSegmentedPager.h"
#import "MXParallaxHeader.h"
#import "MXScrollViewController.h"
#import "RTJAutoQuestionController.h"
#import "RTJAutoLendViewController.h"
#import "RTJAutoBorrowingController.h"
#import "RTJAutoServiceController.h"
#import "RTJAutoMarkButton.h"
#import "RTJAutoMarkLendController.h"

#define  BAR_HEIGHT 64

@interface RTJAutoMarkDetailsController ()<MXSegmentedPagerDelegate,MXSegmentedPagerDataSource,UINavigationBarDelegate,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *jiaxiLab;

@property (weak, nonatomic) IBOutlet UIView  *headView;//头部视图
@property (nonatomic,weak) IBOutlet MXSegmentedPager *segmentedPager;
@property (weak, nonatomic) IBOutlet UILabel *headTitle;
@property (weak, nonatomic) IBOutlet UILabel *rateLab;
@property (weak, nonatomic) IBOutlet UILabel *monthLab;
//@property (weak, nonatomic) IBOutlet UILabel *shouyiLab;
@property (weak, nonatomic) IBOutlet UIView *back_view;
@property (weak, nonatomic) IBOutlet UIView *bg_view;
@property (weak, nonatomic) IBOutlet UILabel *minLab;
@property (nonatomic,strong) RTJAutoServiceController *serviceVC;
@property (nonatomic,strong) RTJAutoBorrowingController *borrowVC;
@property (nonatomic,strong) RTJAutoLendViewController *lendVC;
@property (nonatomic,strong) RTJAutoQuestionController *questionVC;
@property (nonatomic,strong) UIScrollView *scView;
@property (nonatomic,strong) UIButton *btn;
@property (nonatomic,strong) UIButton *btn1;

@property (nonatomic, strong) NSDictionary *dataSource;
@property (nonatomic,strong) NSMutableArray *btnArr;
@property (nonatomic,assign)  BOOL isLoad;

@property (weak, nonatomic) IBOutlet UIView *navigationBarView;
@property (weak, nonatomic) IBOutlet UILabel *nav_title;
@property (strong, nonatomic) IBOutlet UIButton *backButtonItem;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nav_height;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nav_top;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bg_viewWidth;




@end

@implementation RTJAutoMarkDetailsController

-(void)reloadPagers {
    
    if (_serviceVC) {
        [_serviceVC removeFromParentViewController];
        _serviceVC = nil;
    }
    
    if (_borrowVC) {
        [_borrowVC removeFromParentViewController];
        _borrowVC = nil;
    }
    
    if (_lendVC) {
        [_lendVC removeFromParentViewController];
        _lendVC = nil;
    }
    
    if (_questionVC) {
        [_questionVC removeFromParentViewController];
        _questionVC = nil;
    }
    
    [self.segmentedPager reloadData];
}

-(RTJAutoServiceController *)serviceVC {
    if ( ! _serviceVC) {
   
        _serviceVC = [[RTJAutoServiceController alloc] init];
//        _serviceVC.data = self.dataSource;
        [self addChildViewController:_serviceVC];
        [_serviceVC didMoveToParentViewController:self];
    }
    
    return _serviceVC;
}

-(RTJAutoBorrowingController *)borrowVC {
    
    if ( ! _borrowVC) {
 
        _borrowVC = [[RTJAutoBorrowingController alloc] init];
        _borrowVC.data = self.dataSource;
        [self addChildViewController:_borrowVC];
        [_borrowVC didMoveToParentViewController:self];
    }
    
    return _borrowVC;
}

-(RTJAutoLendViewController *)lendVC {
    if ( ! _lendVC) {

        _lendVC = [[RTJAutoLendViewController alloc] init];
        _lendVC.data = self.dataSource;
        [self addChildViewController:_lendVC];
        [_lendVC didMoveToParentViewController:self];
    }
    
    return _lendVC;
}

-(RTJAutoQuestionController *)questionVC {
    if ( ! _questionVC) {
        
        _questionVC = [[RTJAutoQuestionController alloc] init];
        _questionVC.isInfo = 1;
        //        _questionVC.data = self.dataSource;
        [self addChildViewController:_questionVC];
        [_questionVC didMoveToParentViewController:self];
    }
    
    return _questionVC;
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden =  YES;

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _btnArr = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self backview:_back_view viewOfcornerRadius:5];
    self.nav_height.constant = screenH == 812 ? 88 : 64;
    self.nav_top.constant = screenH == 812 ? 52 : 28;
    
    self.segmentedPager.delegate = self;
    self.segmentedPager.dataSource = self;
    self.segmentedPager.bounces = NO;
    self.segmentedPager.backgroundColor = [UIColor whiteColor];
    
    // header view
    self.segmentedPager.parallaxHeader.view = self.headView;
    self.segmentedPager.parallaxHeader.height = 426;
    self.segmentedPager.parallaxHeader.mode = MXParallaxHeaderModeBottom; // 平行底部填充模式
    self.segmentedPager.parallaxHeader.minimumHeight = screenH == 812 ? 98 : 74; // 头部最小高度
    
    // 选择栏控制器属性
    self.segmentedPager.segmentedControl.borderWidth = 1.0; // 边框宽度
    self.segmentedPager.segmentedControl.borderColor = [UIColor redColor]; // 边框颜色
    self.segmentedPager.segmentedControl.frame = CGRectMake(0, 0, screenW, 44); // frame
    self.segmentedPager.segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(-10, 0, 0, 0);// 间距
    self.segmentedPager.segmentedControl.selectionIndicatorHeight =3;// 横条指示器高度
    // 底部指示器的宽度等于内容宽度
    self.segmentedPager.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.segmentedPager.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    self.segmentedPager.segmentedControl.verticalDividerEnabled = NO;// 不可以垂直滚动
    self.segmentedPager.segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
    self.segmentedPager.segmentedControl.selectionIndicatorColor = [UIColor colorForHex:@"#FD3734"];
    // 默认状态的字体
    self.segmentedPager.segmentedControl.titleTextAttributes =
    @{NSForegroundColorAttributeName : [UIColor colorForHex:@"#999999"],
      NSFontAttributeName : [UIFont systemFontOfSize:16]};
    // 选择状态下的字体
    self.segmentedPager.segmentedControl.selectedTitleTextAttributes =
    @{NSForegroundColorAttributeName : [UIColor colorForHex:@"#333333"],
      NSFontAttributeName : [UIFont systemFontOfSize:16]};
    
    self.segmentedPager.segmentedControlEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
//    _bg_viewWidth.constant = screenW;
    NSLog(@"-----%f",_bg_view.width);
   

    
    [self loadData:_markId];

}

// 滚动整体的时候调用
- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didScrollWithParallaxHeader:(MXParallaxHeader *)parallaxHeader
{
    
    CGFloat alpha = [self calcNavigationBarBlendAlpha]<0.25 ? 0 :[self calcNavigationBarBlendAlpha];

    [self setNavigationBarBlendAlpha:alpha animation:YES];
        
}

-(CGFloat)calcNavigationBarBlendAlpha {
    
    UIScrollView *scrollView = (UIScrollView *)self.segmentedPager.subviews[0];
    CGFloat offsetY = scrollView.contentOffset.y;
    
    // 上滑一定距离，导航显示
    return ((screenH == 812 ? -100 : -90)/offsetY);

}

-(void)setNavigationBarBlendAlpha:(CGFloat)alpha animation:(BOOL)animation {
    
    if (animation) {
        [UIView animateWithDuration:UINavigationControllerHideShowBarDuration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            
            self.navigationBarView.alpha = alpha;
            self.backButtonItem.alpha = alpha;
            self.nav_title.alpha = alpha;
            
        } completion:nil];
    }
    
}

#pragma -mark <MXSegmentedPagerDelegate>

- (CGFloat)heightForSegmentedControlInSegmentedPager:(MXSegmentedPager *)segmentedPager
{
    // 指示栏的高度
    return 44.0f;
}

#pragma -mark <MXSegmentedPagerDataSource>

- (NSInteger)numberOfPagesInSegmentedPager:(MXSegmentedPager *)segmentedPager
{
    return 4;
}

- (NSString *)segmentedPager:(MXSegmentedPager *)segmentedPager titleForSectionAtIndex:(NSInteger)index
{
    // 指示栏的文字数组
    return [@[@"服务保险", @"借款列表", @"出借记录",@"常见问题"] objectAtIndex:index];
}

- (UIView *)segmentedPager:(MXSegmentedPager *)segmentedPager viewForPageAtIndex:(NSInteger)index
{
    UIViewController *vc;
    
    switch (index) {
        case 0:
            vc = self.serviceVC;
            break;
            
        case 1:
            vc = self.borrowVC;
            break;
            
        case 2:
            vc = self.lendVC;
            break;
            
        case 3:
            vc = self.questionVC;
            break;
    }
    
    if ( ! vc) {
        return nil;
    }
    return vc.view;
}

- (void)segmentedPager:(MXSegmentedPager *)segmentedPager didSelectViewWithIndex:(NSInteger)index
{
    UIScrollView *scrollView = (UIScrollView *)segmentedPager.subviews[0];
    NSLog(@"%lf",scrollView.contentOffset.x);
    
    if (index==0) {
        
    }else if (index==1) {
        
    }
    else if (index==2) {
        
    }else{
        
        
    }
    
}

-(void)backview:(UIView *)backview viewOfcornerRadius:(NSInteger)cornerRadius{
    
    backview.layer.cornerRadius = cornerRadius;
    backview.layer.shadowColor = [UIColor colorForHex:@"#dbc9cc"].CGColor;
    backview.layer.shadowOffset = CGSizeMake(-1, 1);
    backview.layer.shadowOpacity = 0.5;
    backview.layer.shadowRadius = 5;
    
}

-(void)selectFunctionButtonOfTag:(RTJAutoMarkButton *)btn{
    
    _btn1.selected = NO;
    _isLoad = YES;
    
    if (_btn==nil) {
        
        btn.selected = YES;
        _btn = btn;
        NSArray *arr = _dataSource[@"list"];
        [self loadData:arr[btn.tag-10][@"id"]];
        
    }else if(_btn == btn){
        
        btn.selected = YES;
        _btn = btn;
        
    }else{
        
        _btn.selected = NO;
        btn.selected = YES;
        _btn = btn;
        
        NSArray *arr = _dataSource[@"list"];
        [self loadData:arr[btn.tag-10][@"id"]];
        
    }   
    
}


-(void)loadData:(NSString *)markId{
    
    [SVProgressHUD  showWithStatus:nil];
    
    if (_dataSource == nil) {
        
        [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
        
    }
    
    [RTJNetWork asyncRequestWithURL:@"deals/plan_detail" params:@{@"id":markId} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];

        [self.view removeEmptyView];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.dataSource = data[@"data"];

                [self loadHeaderView:self.dataSource];
                
                [self reloadPagers];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];

                [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    
                    [self loadData:markId];
                }];
                
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{

                [self loadData:markId];
            }];
            
        }
        
    }];
    
    
}

-(void)loadHeaderView:(NSDictionary *)dic{
    
    self.nav_title.text= [NSString stringWithFormat:@"%@",dic[@"name"]];

    self.navigationBarView.alpha = 0;
    self.backButtonItem.alpha = 0;
    self.nav_title.alpha = 0;

    NSString *rate = [NSString stringWithFormat:@"%@",dic[@"rate"]];
    
//    _rateLab.text = [NSString stringWithFormat:@"%@",dic[@"rate"]];
    
    NSString *increase_rate = [NSString stringWithFormat:@"%@",dic[@"increase_rate"]];
    
    if ([increase_rate isEqualToString:@"0.00"]) {
        
        if (rate.length == 2) {
            
            rate = [NSString stringWithFormat:@"%@%@",dic[@"rate"],@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:rate WithLocation:2 frontStr:34 behindStr:20 fontName:NO];

        }else{
            
            rate = [NSString stringWithFormat:@"%@%@",dic[@"rate"],@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:rate WithLocation:1 frontStr:34 behindStr:20 fontName:NO];

        }
        
    }else{
        
        if (rate.length == 2) {
            
            rate = [NSString stringWithFormat:@"%@%@+%@%@",dic[@"rate"],@"%",dic[@"rate"],@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:rate WithLocation:2 frontStr:34 behindStr:20 fontName:NO];
            
            
        }else{
            
            rate = [NSString stringWithFormat:@"%@%@+%@%@",dic[@"rate"],@"%",dic[@"rate"],@"%"];
            _rateLab.attributedText = [self getSubStrNumFromStr:rate WithLocation:1 frontStr:34 behindStr:20 fontName:NO];
            
        }
        
    }
    
    _headTitle.text = [NSString stringWithFormat:@"%@",dic[@"name"]];
    _monthLab.text = [NSString stringWithFormat:@"%@",dic[@"repay_time"]];
    
    NSString *str = [NSString stringWithFormat:@"%@元",dic[@"min_load_money_format"]];
    _minLab.attributedText = [self getSubStrNumFromStr:str WithLocation:str.length-1 frontStr:18 behindStr:12 fontName:YES];

    
    
    //收益 = 投标金额*（预期年化*/100/12）*投资期限
//    CGFloat rete = [dic[@"rate"] floatValue];
//    CGFloat rete1 = [dic[@"increase_rate"] floatValue];
//    CGFloat repay_time = [dic[@"repay_time"] floatValue];
//    CGFloat shouyi = 10000*((rete+rete1)/100/12)*repay_time;
//    NSString *shouyiStr = [NSString stringWithFormat:@"%.2f元",shouyi];
    
//    _shouyiLab.attributedText = [self getSubStrNumFromStr:shouyiStr WithLocation:shouyiStr.length-1 frontStr:18 behindStr:12 fontName:YES];

    
    
    self.scView.backgroundColor = [UIColor whiteColor];
    
    NSArray *arr = dic[@"list"];
    
    CGFloat button1H = 53;
    CGFloat button1W = screenW*83/375;
    
    /// x坐标之间间距
    CGFloat xMargin = screenW*12/375;
    // y坐标之间间距
    CGFloat yMargin = 0;
    // 每行个数
    NSInteger maxClos = [arr count];
    
    for (NSInteger i = 0; i <arr.count ; i++) {
        
        // 行号
        CGFloat row = i / maxClos;
        // 列号
        CGFloat clo = i % maxClos;
        
        RTJAutoMarkButton *titBtn = [RTJAutoMarkButton buttonWithType:UIButtonTypeCustom];
        titBtn.frame =CGRectMake(xMargin+clo*(button1W + xMargin),row*(yMargin+button1H),button1W, button1H);
        [titBtn addTarget:self action:@selector(selectFunctionButtonOfTag:) forControlEvents:UIControlEventTouchUpInside];
        [titBtn setTag:i+10];
        [titBtn setTitle:arr[i][@"repay_time"] forState:UIControlStateNormal];
        [titBtn setTitleColor:[UIColor colorForHex:@"#A0A7CA"] forState:UIControlStateNormal];
        [titBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [titBtn setBackgroundImage:[UIImage imageNamed:@"tzqxhui"] forState:UIControlStateNormal];
        [titBtn setBackgroundImage:[UIImage imageNamed:@"tzqxlioang"] forState:UIControlStateSelected];
        titBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:18];
        
        
        if ([_monthLab.text isEqualToString:titBtn.currentTitle]) {
            
            titBtn.selected  = YES;
            _btn1 = titBtn;
            
        }else{
            
            titBtn.selected  = NO;

        }        
        if ( _isLoad == NO) {
            
            [self.scView addSubview:titBtn];

        }
        
    }
    
    _scView.contentSize = CGSizeMake(arr.count*(button1W + xMargin)+xMargin, 0);
    
}

- (NSMutableAttributedString *)getSubStrNumFromStr:(NSString *)str WithLocation:(NSInteger) index frontStr:(CGFloat) font1 behindStr:(CGFloat)font2 fontName:(BOOL)fontName{
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:str];
    
    [AttributedStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFang-SC-Medium" size:font1] range:NSMakeRange(0, index)];
    
    [AttributedStr addAttribute:NSFontAttributeName value:fontName ? [UIFont fontWithName:@"PingFang-SC-Regular" size:font2]:[UIFont fontWithName:@"PingFang-SC-Medium" size:font2] range:NSMakeRange(index, str.length-index)];
    
    return AttributedStr;
    
}

- (IBAction)back:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)lendout:(UIButton *)sender {
    
    if ([RTJUserTool isLogin]) {

        RTJAutoMarkLendController *vc = [[RTJAutoMarkLendController alloc]init];
        vc.titleStr = self.dataSource[@"name"];
        vc.rateStr = [NSString stringWithFormat:@"%@",self.dataSource[@"rate"]];
        vc.rebateStr = [NSString stringWithFormat:@"%@",self.dataSource[@"increase_rate"]];
        vc.timeStr = [NSString stringWithFormat:@"%@",self.dataSource[@"repay_time"]];
        vc.max_mon = [NSString stringWithFormat:@"%@",self.dataSource[@"max_load_money_format"]];
        vc.min_mon = [NSString stringWithFormat:@"%@",self.dataSource[@"min_load_money_format"]];
        vc.idStr = [NSString stringWithFormat:@"%@",self.dataSource[@"id"]];
        [self.navigationController pushViewController:vc animated:YES];

    }else{
        
        RTJLoginOrRegisterController *vc = [[RTJLoginOrRegisterController alloc]init];
        LXNavigationViewController *nav=[[LXNavigationViewController alloc]initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        
    }
  
}



-(UIScrollView *)scView{
    
    if (!_scView) {
      
        _scView = [[UIScrollView alloc]initWithFrame:_bg_view.bounds];
        _scView.showsHorizontalScrollIndicator = NO;
        [_bg_view addSubview:_scView];
    }
    
    return _scView;
}


@end
